package com.example.juejincheck.utils;

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

public class HttpUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * get请求(用于key-value格式的参数,且带有header请求头)
     *
     * @param url
     * @param paramMap 请求的参数map<key,value>键值对
     * @param headerMap header参数 map<key,value>键值对
     * @return
     */
    public static String doGet(String url, Map<String, String> paramMap, Map<String, String> headerMap) {
        String result = null;
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            /*
             * 由于GET请求的参数都是拼装在URL地址后方，所以我们要构建一个URL，带参数
             */
            URIBuilder uriBuilder = new URIBuilder(url);

            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }

            //拼接请求头参数
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
            // 执行请求
            response = httpClient.execute(httpGet);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            if (entity != null) {
                // 将返回结果处理成String对象
                result = EntityUtils.toString(entity, "UTF-8");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    

    public static String doLogin(String loginUrl, String phoneNum, String password){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(loginUrl);
            JSONObject json = new JSONObject();
            json.put("phoneNum", phoneNum);
            json.put("password", password);
            // 创建请求内容
            StringEntity entity = new StringEntity(JSONObject.toJSONString(json), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            log.info("登录结果：{}", resultString);
            if(jsonObject.getBoolean("success")){
                Header[] headers = response.getHeaders("Authorization");
                String result = "";
                for (int i = 0; i < headers.length; i++) {
                    Header header = headers[i];
                    result = "token="+header.getValue().replace("Bearer ", "Bearer%20")+"; ";
                    log.info(header.getName()+"==================="+header.getValue());
                }
                Header[] headers1 = response.getHeaders("Set-Cookie");
                for (int i = 0; i < headers1.length; i++) {
                    Header header = headers1[i];
                    if(header.getValue().contains("JSESSIONID")){
                        result += header.getValue().replaceAll(" Path=/; HttpOnly", "");
                    }
                    log.info(header.getName()+"==================="+header.getValue());
                }
                return result;
            }
        } catch (Exception e) {
            log.error("登录失败",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("登录失败",e);
            }
        }
        return null;
    }
    public static String doPost(String url, String param) {

        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
            {
                if (line != null && !"".equals(line.trim()))
                {
                    result.append(new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }
    
    /**
     * 发送post请求
     * @param URL
     * @param json
     *
     * @return
     */
    public static String sendPost(String URL,String cookie, JSONObject json) {
        String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        if(!StringUtils.isEmpty(cookie)){
            post.addHeader("Cookie", cookie);
        }
        post.addHeader("User-Agent", userAgent);
        post.addHeader("Content-Type", "application/json; charset=UTF-8");
        post.addHeader("Cache-Control", "no-cache");
        post.addHeader("connection", "Keep-Alive");
        post.addHeader("accept", "*/*");
        String result;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功，做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
//            logger.error("请求异常："+e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 从连接池中获取连接的超时时间--10s
     */
    private static int connectionRequestTimeout = 10000;
    /**
     * 客户端和服务器建立连接的超时时间--握手连接时间--10s
     */
    private static int connectTimeout = 60000;
    /**
     * 从对方服务接受响应流的时间
     */
    private static int socketTimeout = 60000;
    /**
     * 连接池最大连接数
     */
    private static int maxTotal = 800;
    /**
     * 每个主机的并发
     */
    private static int maxPerRoute = 20;
    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static CloseableHttpClient httpClient;

    public static CloseableHttpClient getClient() {
        return httpClient;
    }

    static {
        log.info("初始化http connection 连接池 ...");
        try {
            // 配置同时支持 HTTP 和 HTPPS
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslConnectionSocketFactory).build();
            connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            log.error("初始化http 连接池异常", e);
            connectionManager = new PoolingHttpClientConnectionManager();
        }
        //连接池统一配置
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(maxPerRoute);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();

        //不做重试功能
        HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(0, false);

        httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build();

        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(10);
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            connectionManager.closeExpiredConnections();
            connectionManager.closeIdleConnections(20, TimeUnit.SECONDS);
            log.info("回收过期的http连接完成 status：{}", connectionManager.getTotalStats());
        }, 30, 120, TimeUnit.SECONDS);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("关闭 httpClient 连接");
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("关闭 httpClient 异常", e);
            }
        }));
    }
    /**
     * post请求提交form-data上传文件
     *
     * @param url
     * @param headers 请求头
     * @return
     */
    public static String doPostUploadFile(String url, Map<String, String> headers, File file, Map<String, String> param) {
        HttpPost httpPost = new HttpPost(url);
        packageHeader(headers, httpPost);
        String fileName = file.getName();

        CloseableHttpResponse response = null;

        String respContent = null;

        long startTime = System.currentTimeMillis();

        // 设置请求头 boundary边界不可重复，重复会导致提交失败
        String boundary = "-------------------------" + UUID.randomUUID().toString();
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

        // 创建MultipartEntityBuilder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // 设置字符编码
        builder.setCharset(StandardCharsets.UTF_8);
        // 模拟浏览器
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // 设置边界
        builder.setBoundary(boundary);
        // 设置multipart/form-data流文件
        builder.addPart("file", new FileBody(file));
        // application/octet-stream代表不知道是什么格式的文件
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.addTextBody(entry.getKey(), entry.getValue(), contentType);
        }

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);

        try {
            response = httpClient.execute(httpPost);
            if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() < 400) {
                HttpEntity he = response.getEntity();
                if (he != null) {
                    respContent = EntityUtils.toString(he, "UTF-8");
                }
            } else {
                log.error("对方响应的状态码不在符合的范围内!");
                throw new RuntimeException();
            }
            return respContent;
        } catch (Exception e) {
            log.error("网络访问异常,请求url地址={},响应体={},error={}", url, response, e);
            throw new RuntimeException();
        } finally {
            log.info("统一外网请求参数打印,post请求url地址={},响应={},耗时={}毫秒", url, respContent, (System.currentTimeMillis() - startTime));
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("请求链接释放异常", e);
            }
        }
    }

    /**
     * 封装请求头
     *
     * @param paramsHeads
     * @param httpMethod
     */
    private static void packageHeader(Map<String, String> paramsHeads, HttpRequestBase httpMethod) {
        if (!CollectionUtils.isEmpty(paramsHeads)) {
            Set<Map.Entry<String, String>> entrySet = paramsHeads.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 发送post请求
     * @param URL
     * @param json
     *
     * @return
     */
    public static String sendDelete(String URL,String cookie, JSONObject json) {
        String userAgent = "okhttp/3.12.1;jdmall;android;version/10.3.4;build/92451;";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpDelete post = new HttpDelete(URL);
        post.addHeader("Cookie", cookie);
        post.addHeader("User-Agent", userAgent);
        post.addHeader("Content-Type", "application/json; charset=UTF-8");
        post.addHeader("Cache-Control", "no-cache");
        post.addHeader("connection", "Keep-Alive");
        post.addHeader("accept", "*/*");
        String result;
        try {
//            StringEntity s = new StringEntity(json.toString(), "utf-8");
//            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
//                    "application/json"));
//            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功，做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
//            logger.error("请求异常："+e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }
    /**
     * 发送post请求
     * @param URL
     * @param json
     *
     * @return
     */
    public static String sendPostAuthorization(String URL,String authorization, String gameId, JSONObject json) {
        String userAgent = "okhttp/3.12.1;jdmall;android;version/10.3.4;build/92451;";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.addHeader("authorization", "Bearer "+authorization);
        if(!StringUtils.isEmpty(gameId)){
            post.addHeader("x-tt-gameid", gameId);
        }
        post.addHeader("User-Agent", userAgent);
        post.addHeader("Content-Type", "application/json; charset=UTF-8");
        post.addHeader("Cache-Control", "no-cache");
        post.addHeader("connection", "Keep-Alive");
        post.addHeader("accept", "*/*");
        String result;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功，做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
//            logger.error("请求异常："+e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    
}